#ifndef __WHISPER_PROCESSOR_H__
#define __WHISPER_PROCESSOR_H__

#include "common.h"

// FIX: remove
#include <iostream>

#include "whisper.h"
#include "grammar-parser.h"

#include <cmath>
#include <fstream>
#include <cstdio>
#include <regex>
#include <string>
#include <thread>
#include <vector>
#include <cstring>
#include <QObject>
#include <QThread>
#include <QString>

#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#endif

#if defined(_MSC_VER)
#pragma warning(disable: 4244 4267) // possible loss of data
#endif

// command-line parameters
struct whisper_params {
    // 各种数值型参数，用于配置模型运行时的行为
    int32_t n_threads     = std::min(4, (int32_t) std::thread::hardware_concurrency());
    int32_t n_processors  = 1;
    int32_t offset_t_ms   = 0;
    int32_t offset_n      = 0;
    int32_t duration_ms   = 0;
    int32_t progress_step = 5;
    int32_t max_context   = -1;
    int32_t max_len       = 0;
    int32_t best_of       = whisper_full_default_params(WHISPER_SAMPLING_GREEDY).greedy.best_of;
    int32_t beam_size     = whisper_full_default_params(WHISPER_SAMPLING_BEAM_SEARCH).beam_search.beam_size;
    int32_t audio_ctx     = 0;
    // 采样和过滤参数
    float word_thold      =  0.01f;
    float entropy_thold   =  2.40f;
    float logprob_thold   = -1.00f;
    float no_speech_thold =  0.6f;
    float grammar_penalty = 100.0f;
    float temperature     = 0.0f;
    float temperature_inc = 0.2f;
    // 布尔型参数控制不同功能开关
    bool debug_mode      = false;
    bool translate       = false;
    bool detect_language = false;
    bool diarize         = false;
    bool tinydiarize     = false;
    bool split_on_word   = false;
    bool no_fallback     = false;
    bool output_txt      = false;
    bool output_vtt      = false;
    bool output_srt      = false;
    bool output_wts      = false;
    bool output_csv      = false;
    bool output_jsn      = false;
    bool output_jsn_full = false;
    bool output_lrc      = false;
    bool no_prints       = false;
    bool print_special   = false;
    bool print_colors    = false;
    bool print_progress  = false;
    bool no_timestamps   = false;
    bool log_score       = false;
    bool use_gpu         = true;
    bool flash_attn      = false;
    bool suppress_nst    = false;

    // 字符串型参数配置
    std::string language  = "zh";// 识别语言
    std::string prompt;         // 初始提示文本
    std::string font_path = "/System/Library/Fonts/Supplemental/Courier New Bold.ttf";
    std::string model     = "resouce/model/ggml-medium.bin";   // 模型文件路径
    std::string grammar;
    std::string grammar_rule;

    // 额外的说话人转折字符串，用于语音分离（diarization）
    std::string tdrz_speaker_turn = " [SPEAKER_TURN]"; // TODO: set from command line

    // 正则表达式，用于匹配需要被抑制的 token
    std::string suppress_regex;
    // OpenVINO 相关设备设置（如 CPU）
    std::string openvino_encode_device = "CPU";

    std::string dtw = "";

    // 输入输出文件列表
    std::vector<std::string> fname_inp = {};
    std::vector<std::string> fname_out = {};

    grammar_parser::parse_state grammar_parsed;
};

Q_DECLARE_METATYPE(whisper_params)

struct whisper_print_user_data {
    const whisper_params * params;

    const std::vector<std::vector<float>> * pcmf32s;
    int progress_prev;
};

// 段落结果结构体!
struct SegmentResult {
    int sequence;     // 段落序号
    QString startTime; // 开始时间戳
    QString endTime;   // 结束时间戳
    QString speaker;   // 说话人标识
    QString text;      // 文本内容

    SegmentResult() {}
    SegmentResult(int seq, QString start, QString end, QString spk, QString txt)
        : sequence(seq), startTime(start), endTime(end), speaker(spk), text(txt) {}
};

Q_DECLARE_METATYPE(SegmentResult)
Q_DECLARE_METATYPE(QList<SegmentResult>)

class WhisperWorker : public QObject {
    Q_OBJECT

public:
    explicit WhisperWorker(QObject *parent = nullptr)
        : QObject(parent), ctx(nullptr) {}

    ~WhisperWorker() {
        if (ctx) whisper_free(ctx);
    }

public slots:
    // 初始化模型
    void initialize(const QString &modelPath, const whisper_params &params);

    // 提交音频处理任务
    void processAudio(const QString &audioPath);
    void processVideoAudio(const QString &audioPath);  // 专门用于视频字幕提取

signals:
    void initializationFinished(bool success);
    void progressUpdated(int percent);
    void processingFinished(const QList<SegmentResult>& segments);
    void errorOccurred(const QString &message);
    void audioProcessingFinished(const QList<SegmentResult>& segments);
    void videoProcessingFinished(const QList<SegmentResult>& segments);
    
private:
    whisper_params m_params;
    whisper_context* ctx;
};

// 使用示例
class Whisper : public QObject {
    Q_OBJECT
public:
    Whisper() {
        m_worker = new WhisperWorker;
        m_thread = new QThread;

        m_worker->moveToThread(m_thread);

        connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
        connect(this, &Whisper::startProcessing, m_worker, &WhisperWorker::processAudio);

        m_thread->start();
    }

    ~Whisper() {
        m_thread->quit();
        m_thread->wait();
    }

    // void initializeModel(const QString &modelPath) {
    void initializeModel() {
        whisper_params params;
        QString modelPath = "resource/model/ggml-medium.bin";
        // 初始化参数...
        QMetaObject::invokeMethod(m_worker, "initialize", 
                                Qt::QueuedConnection,
                                Q_ARG(QString, modelPath),
                                Q_ARG(whisper_params, params));
    }

    void processFile(const QString &audioPath) {
        emit startProcessing(audioPath);
    }

    WhisperWorker* m_worker;
    QThread* m_thread;

signals:
    void startProcessing(const QString &path);

private:
};

int test_main();

#endif // __WHISPER_PROCESSOR_H__
